package movieGandalf.dbParser;

import java.io.BufferedReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import movieGandalf.database.MovieTools;
import movieGandalf.logicGuiConnection.Gender;

public class ActorsReader implements DataReader{
	
	private Gender gender = null;
	
	public ActorsReader(Gender gender){
		this.gender = gender;
	}
	
	public int read(Connection conn, BufferedReader in){
		String line = null;
		List<String> actorNames = new LinkedList<String>();
				
		try {
			boolean isBegin = true;
			
			while ((line = in.readLine()) != null){
				
				if (isBegin){
					line=line.trim();
					int len=line.length();
					
					if (len<6 || !line.subSequence(0, 4).equals("Name") || !line.subSequence(len-6, len).equals("Titles"))
						continue;
					else{
						isBegin = false;
						line = in.readLine();
						continue;
					}
				}
				
				int len=line.length();
				
				if (len>=5 && line.startsWith("-----"))
					break;
				
				int i = 0;
				for (i=0;i<len;i++){
					if (line.charAt(i)=='\t') {
						break;
					}
				}
				
				if (i==0)
					continue;
				else if (i==len)
					i = len - 1;
				
				String actor = line.substring(0, i).trim();
				if (!MovieTools.actorValidator(actor))
					continue;
				
				try{
					actorNames.add(actor);
				}
				catch (Exception e){
					e.getMessage();
				}
			}

			PreparedStatement stmt = conn.prepareStatement(new String("REPLACE INTO Actors (actorName,imdbName,gender) VALUES (?,?,?)"));
			
			Iterator<String> iter = actorNames.iterator();
			String actorName = null;
			
			while (iter.hasNext()){
				actorName = iter.next();
				stmt.setString(1, actorName);
				stmt.setString(2, actorName);
				if (gender.equals(Gender.FEMALE))
					stmt.setString(3, "Female");
				else
					stmt.setString(3, "Male");
				stmt.addBatch();
			}
			try{
				stmt.executeBatch();
			}
			catch(Exception e){}
			finally{
				conn.commit();
				stmt.close();
			}
		}
		
		catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			try{
				in.close();
			}
			catch(Exception e){
				return 0;
			}
		}
		
		return 1;
	}
	
}
